layui.use(['form','upload'], function () {
    let form = layui.form,
        layer = layui.layer,
        upload = layui.upload,
        $ = layui.$;


    //单图片拖拽上传
    let uploadInst = upload.render({
        elem: '#headImg',
        url: '/admin/category/Doupload',
        size: 500,
        field: 'thumb_img',
        accept: 'images',
        acceptMime: 'image/*',
        before: function(obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result) {
                $('#imgurl').attr('src', result); //图片链接（base64）;
            });
            this.data = {
                'mark': 'img',
                'field': 'thumb_img',
                'oldSrc': $("#imgurlHidden").val()
            };
        },
        done: function(res) {
            console.log( $("#imgurlHidden").val())
            //如果上传失败
            if (res.status == false) {
                return layer.msg('上传失败');
            }
            //上传成功
            //打印后台传回的地址: 把地址放入一个隐藏的input中, 和表单一起提交到后台, 此处略..
            // window.parent.uploadHeadImage(res.src);
            $("#imgurlHidden").val(res.src);
            let demoText = $('#demoText');
            demoText.html('<span style="color: #8f8f8f;">上传成功!!!</span>');
        },
        error: function() {
            //演示失败状态，并实现重传
            let demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function() {
                uploadInst.upload();
            });
        },

    });

    //监听提交
    form.on('submit(saveBtn)', function (data) {

        let  postdata =data.field

        //发异步，把数据提交给php
        $.ajax({
            url: '/admin/spearea/Save?action=ajax',
            type: 'post',
            dataType: 'json',
            data:postdata,
            success: function(res) {
                console.log( res)

                if (res.status == true) {
                    layer.msg('保存成功', {icon: 1, time: 1000},
                        function(){
                            parent.location.reload();
                        })

                }  else {
                    layer.open({
                        title: '错误信息',
                        content: '<span style="color:red">'+res.code+':</span>'+res.msg
                    })
                    return false
                }
            },
            error: function(re) {

                layer.open({
                    title: '错误信息',
                    content: '<span style="color:red">'+re.responseJSON.errorCode+':</span>'+re.responseJSON.msg
                })
            }
        });




    });

});


function delcycle (obj){
    $(obj).parents('.layui-form-item').remove();
}